package GUILayer;
import ControlLayer.*;
import ModelLayer.*;

import java.awt.Color;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;

import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.ArrayList;
import java.util.Date;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;

import ModelLayer.DataHolder;

import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;

public class InvoiceDetails extends JFrame {

        private JPanel contentPane;
        private JTable table;
        private JTextField txtDiscount;
        private String date;
        private JLabel lblShowId;
        private DataHolder dataHolder;
        private Print print;
        private JTextField txtDate;
        private JTextField txtDue;
        private JTextField txtCustomer;
        private JTextField txtEmployee;
        private JTextField txtDeliveryId;
        private ArrayList<SalesLine> salesLines;
        private JComboBox comboBox;
        private SalesOrder so;
        
        private IFSearch search;
    	private IFUpdate update;
        
        /**
         * Create the frame.
         */
        public InvoiceDetails(SalesOrder salesorder) {
        	so = salesorder;
        	search = new SearchControler();
        	update = new UpdateControler();
        	
    		setResizable(false);
            setTitle("Invoice");
            setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            setBounds(150, 50, 390, 530);
            contentPane = new JPanel();
            contentPane.setBackground(new Color(255, 255, 204));
            contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
            setContentPane(contentPane);
            contentPane.setLayout(null);
            
            JLabel lblId = new JLabel("ID:");
            lblId.setBounds(10, 11, 100, 14);
            contentPane.add(lblId);
            
            lblShowId = new JLabel(Integer.toString(so.getId()));
            lblShowId.setBounds(96, 11, 89, 14);
            contentPane.add(lblShowId);
            
            JLabel lblDate = new JLabel("Date:");
            lblDate.setBounds(10, 36, 100, 14);
            contentPane.add(lblDate);
            
            JLabel lblPaymentDeadline = new JLabel("Payment due:");
            lblPaymentDeadline.setBounds(10, 61, 100, 14);
            contentPane.add(lblPaymentDeadline);
            
            JLabel lblCustomer = new JLabel("Customer:");
            lblCustomer.setBounds(10, 86, 100, 14);
            contentPane.add(lblCustomer);
            
            JLabel lblEmployee = new JLabel("Employee:");
            lblEmployee.setBounds(10, 111, 100, 14);
            contentPane.add(lblEmployee);
                            
            JLabel lblProducts = new JLabel("Products:");
            lblProducts.setBounds(10, 136, 100, 14);
            contentPane.add(lblProducts);
            
            JScrollPane scrollPane = new JScrollPane();
            scrollPane.setBounds(10, 161, 364, 200);
            contentPane.add(scrollPane);
            
            salesLines = so.getSalesLine();
            table = new JTable();
            table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            table.setFillsViewportHeight(true);
            setTableOfProducts(table, salesLines);
            table.getColumnModel().getColumn(0).setResizable(false);
            table.getColumnModel().getColumn(1).setResizable(false);
            table.getColumnModel().getColumn(2).setResizable(false);
            table.getColumnModel().getColumn(3).setResizable(false);
            table.getColumnModel().getColumn(4).setResizable(false);
            scrollPane.setViewportView(table);
            
            JLabel lblDiscount = new JLabel("Discount:");
            lblDiscount.setBounds(10, 369, 100, 14);
            contentPane.add(lblDiscount);
            
            txtDiscount = new JTextField(Integer.toString(so.getDiscount()));
            txtDiscount.setBounds(174, 366, 89, 20);
            contentPane.add(txtDiscount);
            txtDiscount.setColumns(10);
            
            JLabel lblTotal = new JLabel("Total:");
            lblTotal.setBounds(10, 440, 46, 14);
            contentPane.add(lblTotal);
            
            JLabel lblDelivery = new JLabel("Delivery:");
            lblDelivery.setBounds(10, 394, 46, 14);
            contentPane.add(lblDelivery);
            
            JLabel lblTotalPrice = new JLabel(Double.toString(so.getTotal()));
            lblTotalPrice.setBounds(174, 440, 89, 14);
            contentPane.add(lblTotalPrice);
            
            JButton btnSave = new JButton("Save");
            btnSave.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
//                              print = new Print();
//                              print.setVisible(true);
                            saveInvoiceModifications(txtDue.getText(), Integer.parseInt(txtDiscount.getText()), Integer.parseInt(txtDeliveryId.getText()), comboBox.getSelectedItem().toString());
                            dispose();
                    }
            });
            btnSave.setBounds(10, 465, 89, 23);
            contentPane.add(btnSave);
            
            JButton btnCancel = new JButton("Cancel");
            btnCancel.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent e) {
                            dispose();
                    }
            });
            btnCancel.setBounds(285, 465, 89, 23);
            contentPane.add(btnCancel);
            
            txtDate = new JTextField(DateFormat.getInstance().format(so.getCreationDate()).substring(0,8));
            txtDate.setEditable(false);
            txtDate.setBounds(96, 33, 86, 20);
            contentPane.add(txtDate);
            txtDate.setColumns(10);
            
            txtDue = new JTextField(DateFormat.getInstance().format(so.getPaymentDate()).substring(0,8));
            txtDue.setBounds(96, 58, 86, 20);
            contentPane.add(txtDue);
            txtDue.setColumns(10);
            
            txtCustomer = new JTextField(Integer.toString(so.getCustomer().getId()));
            txtCustomer.setEditable(false);
            txtCustomer.setBounds(96, 83, 86, 20);
            contentPane.add(txtCustomer);
            txtCustomer.setColumns(10);
            
            txtEmployee = new JTextField(Integer.toString(so.getEmployee().getId()));
            txtEmployee.setEditable(false);
            txtEmployee.setBounds(96, 108, 86, 20);
            contentPane.add(txtEmployee);
            txtEmployee.setColumns(10);
            
            txtDeliveryId = new JTextField(Integer.toString(so.getDelivery().getDeliveryId()));
            txtDeliveryId.setBounds(174, 391, 89, 20);
            contentPane.add(txtDeliveryId);
            txtDeliveryId.setColumns(10);
            
            JLabel lblStatus = new JLabel("Status:");
            lblStatus.setBounds(10, 419, 57, 14);
            contentPane.add(lblStatus);
            
            comboBox = new JComboBox();
            comboBox.setModel(new DefaultComboBoxModel(new String[] {"Created", "In progress", "Delivered", "Canceled"}));
            comboBox.setBounds(174, 416, 89, 20);
            contentPane.add(comboBox);
            switch(so.getStatus())
            {
                    case "created": comboBox.setSelectedIndex(0);
                            break;
                    case "in progress": comboBox.setSelectedIndex(1);
                            break;
                    case "delivered": comboBox.setSelectedIndex(2);
                            break;
                    case "canceled": comboBox.setSelectedIndex(3);
                            break;
            }
            
        }
        
        private void setTableOfProducts(JTable jTable, ArrayList<SalesLine> salesLine) {
                DefaultTableModel model = new DefaultTableModel();
            jTable.setModel(model);
            model.setColumnIdentifiers(new String[]{"ID", "Name", "Price", "Quantity", "Subtotal"});
            for (SalesLine s : salesLine) {
                double subtotal = (s.getP().getNettPrice() + s.getP().getNettPrice() * s.getP().getTax() / 100 ) * s.getQuantity();
                model.addRow(new String[]{Integer.toString(s.getP().getId()), s.getP().getName(), Double.toString(s.getP().getNettPrice()),Integer.toString(s.getQuantity()), Double.toString(subtotal)});
            }
                
        }

        private void saveInvoiceModifications(String due, int discount, int deliveryId, String status)
        {
        	Date dD = new Date();
        	boolean date = false;
        	SimpleDateFormat formatter =  new SimpleDateFormat("dd/mm/yy");
			try {
				dD = formatter.parse(due);
			} catch (ParseException e) {
				JOptionPane.showMessageDialog(null,
                        "Date not valid!",
                        "Warning",
                        JOptionPane.WARNING_MESSAGE);
				e.printStackTrace();
				date = true;
			}
			if(!date)
			{
				so.setPaymentDate(dD);
				so.setDelivery(search.getDeliveryById(deliveryId));
				so.setDiscount(discount);
				so.setStatus(status);
				update.updateOrder(so);
				MainWindow.getInstance().refreshTableInvoice();
				dispose();
			}
        }
}